package com.magenta.maxoptra.gis.distancematrix;

import com.magenta.maxoptra.gis.GeoProviderSettings;
import com.magenta.maxoptra.gis.commons.Pair;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalTime;

/**
 * @author Sergey Grachev
 */
public final class GroupContext {

    private final long id;
    private volatile boolean locked;
    private volatile boolean allowUpdating;
    private int requestsDelay;
    private GeoProviderSettings geoProviderSettings;
    private Pair<LocalTime, LocalTime> timeInterval;

    public GroupContext(final long id) {
        this.id = id;
    }

    public void lock() {
        synchronized (this) {
            locked = true;
        }
    }

    public void unlock() {
        synchronized (this) {
            locked = false;
        }
    }

    public long getId() {
        return id;
    }

    public void setRequestsDelay(final int requestsDelay) {
        this.requestsDelay = requestsDelay;
    }

    public void stopUpdating() {
        allowUpdating = false;
    }

    public void startUpdating() {
        allowUpdating = true;
    }

    public GeoProviderSettings getGeoProviderSettings() {
        return geoProviderSettings;
    }

    public void setGeoProviderSettings(final GeoProviderSettings geoProviderSettings) {
        this.geoProviderSettings = geoProviderSettings;
    }

    public boolean isAllowUpdating() {
        return allowUpdating;
    }

    public boolean isDisabled() {
        return !allowUpdating || locked;
    }

    public Pair<LocalTime, LocalTime> getTimeInterval() {
        return timeInterval;
    }

    public void setTimeInterval(final int from, final int to) {
        this.timeInterval = new Pair<LocalTime, LocalTime>(
                new LocalTime(DateTimeZone.UTC).withMillisOfDay(from),
                new LocalTime(DateTimeZone.UTC).withMillisOfDay(to));
    }

    @Override
    public String toString() {
        return "GroupContext{" +
                "id=" + id +
                ", locked=" + locked +
                ", allowUpdating=" + allowUpdating +
                ", requestsDelay=" + requestsDelay +
                ", geoProviderSettings=" + geoProviderSettings +
                ", timeInterval=" + timeInterval +
                '}';
    }
}
